package team.first.movieapiv1pro.controller;

/**
 * @Author: HAPPY
 * @Project_name: project
 * @Package_name: team.first.movie_api.controller
 * @Date: 2021/10/3 15:14
 */

import cn.hutool.core.date.DateTime;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import team.first.movieapiv1pro.domain.Comment;
import team.first.movieapiv1pro.service.CommentService;
import team.first.movieapiv1pro.vo.ApiResponse;
import team.first.movieapiv1pro.vo.ApiResponsePaging;
import team.first.movieapiv1pro.vo.ResponseComment;

import java.util.List;

@RestController
public class CommentController {
    @Autowired
    CommentService commentService;

    /**
     * 1.6 获取指定编号的电影评论
     * 接口地址:GET /api/v1/movie/{id}/comments
     */
    @ApiOperation("1.6 GET： 获取指定编号的电影评论")
    @GetMapping("/api/v1/movie/{id}/comments")
    public ApiResponsePaging<List<ResponseComment>> movieComments(@ApiParam("电影编号") @PathVariable("id") Integer id) {
        ApiResponsePaging<List<ResponseComment>> apiResponsePaging = new ApiResponsePaging<>();
        try {
            List<ResponseComment> responseCommentsData = commentService.findAllCommentsByMovieId(id);
            int totalRow = responseCommentsData.size();

            apiResponsePaging.setData(responseCommentsData).setPageSize(20).setPageNumber(1).setTotalPage(responseCommentsData.size())
                    .setCode(200).setMessage("请求成功").setSuccess(true).setTotalRow(totalRow);
        } catch (Exception e) {
            e.printStackTrace();
            apiResponsePaging.setCode(500).setSuccess(false).setMessage("请求失败");
        }
        return apiResponsePaging;
    }

    /**
     *  2.3 POST 用户对指定电影进行评论
     * @param comment 评论信息
     * @return 返回评论后的信息
     */
    @ApiOperation(value = "2.3 POST 对电影进行评论，返回评论后的电影信息")
    @PostMapping("/api/v1/comment")
    public ApiResponse<Integer> comment(@ApiParam("评论信息") Comment comment) {
        ApiResponse<Integer> apiResponse = new ApiResponse<>();

        try {
            comment.setCreatedAt(new DateTime().toString());
            // 添加评论
            commentService.save(comment);

            // 评论成功后返回电影的 id，前端拿到id再发一个查询的请求进行查询
            apiResponse.setCode(200).setSuccess(true).setMessage("评论成功").setData(comment.getMovieId());
        } catch (Exception e) {
            e.printStackTrace();
            apiResponse.setCode(500).setSuccess(false).setMessage("请求失败");
        }

        return apiResponse;
    }
}
